package zju.ccnt.rest.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import zju.ccnt.rest.api.ApiBusinessUser;
import zju.ccnt.rest.service.BusinessUserServiceImpl;
import zju.ccnt.oauth2.Role;
import zju.ccnt.oauth2.user.api.ChangePasswordRequest;
import zju.ccnt.oauth2.user.api.CreateUserRequest;
import zju.ccnt.oauth2.user.api.CreateUserResponse;

import java.security.Principal;

/**
 * Created by zha on 14/11/2.
 * API for business_uer
 */
@RestController
@RequestMapping("/business_user")
public class BusinessUserController {


    private BusinessUserServiceImpl businessUserService;

    private static final String ASK_ACCESS_TOKEN_CALL_BACK_URI = "/oauth/token";

    @Autowired
    public BusinessUserController(final BusinessUserServiceImpl businessUserService) {
        this.businessUserService = businessUserService;
    }

    @RequestMapping( method = RequestMethod.POST)
    @Transactional
    /**
     * Create a new business_user
     * Return:
     *     ApiBusinessUser : contains basic info
     *     callbackUrI: uri after register to get the access_token
     */
    public ResponseEntity<CreateUserResponse> createBusinessUser(@RequestBody CreateUserRequest<ApiBusinessUser> createBusinessUserRequest) {
        ApiBusinessUser apiBusinessUser = businessUserService.createUser(createBusinessUserRequest, Role.BUSINESS);
        CreateUserResponse<ApiBusinessUser> response = new CreateUserResponse<ApiBusinessUser>(
                apiBusinessUser,ASK_ACCESS_TOKEN_CALL_BACK_URI
        );

        return new ResponseEntity<CreateUserResponse>(response, HttpStatus.OK);
    }

    @RequestMapping(value = "/password", method = RequestMethod.POST)
    @PreAuthorize(value="hasRole('BUSINESS')")
    @Transactional
    public ResponseEntity<String> changeBusinessUserPassword(@RequestBody ChangePasswordRequest passwordRequest, Authentication authentication) {
        businessUserService.updateUserPassword(passwordRequest, authentication);
        return new ResponseEntity<String>(ASK_ACCESS_TOKEN_CALL_BACK_URI, HttpStatus.OK);
    }

    @ResponseBody
    @RequestMapping(value = "/myself", method = RequestMethod.GET)
    @PreAuthorize(value = "hasRole('BUSINESS')")
    public ApiBusinessUser getMyself(Principal principal){
        return businessUserService.getUser(principal.getName());
    }

}
